package com.cxf.windex.rest;

import com.cxf.windex.base.msg.ObjectRestResponse;
import com.cxf.windex.base.msg.TableResultResponse;
import com.cxf.windex.base.rest.BaseRestController;
import com.cxf.windex.base.util.DateUtil;
import com.cxf.windex.base.util.IdUtil;
import com.cxf.windex.biz.JsBillsBiz;
import com.cxf.windex.entity.JsBills;
import com.cxf.windex.enums.BillEnum;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author chenxf
 * @date 3/16/2018
 * @description
 */
@Api(tags = {"小程序 - 记账本接口"})
@Controller
@RequestMapping("/user/bill")
public class BillController extends BaseRestController<JsBillsBiz, JsBills> {


  @ApiOperation(value = "查询账本记录", notes = "查询账本记录")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "limit", value = "记录数", required = false, paramType = "query", dataType = "int"),
      @ApiImplicitParam(name = "offset", value = "页码", required = false, paramType = "query", dataType = "int"),
      @ApiImplicitParam(name = "orderStr", value = "排序 desc", required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "name", value = "名称", required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "yearMonth", value = "年月2018-03", required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "payType", value = "类型：0收入 1支出", required = false, paramType = "query", dataType = "String")
  })
  @RequestMapping(value = "/list", method = RequestMethod.GET)
  @ResponseBody
  public TableResultResponse<JsBills> list(
          @RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1") int offset,
          @RequestParam(defaultValue = "desc") String orderStr, String name, String yearMonth,
          String payType) {

    String userId = this.getCurrentUserId();

    if ( userId==null || userId.equals("") ) {
      return new TableResultResponse<JsBills>(0, offset, limit,new ArrayList<JsBills>());

    }
    Example example = new Example(JsBills.class);
    Criteria criteria = example.createCriteria();
    if (StringUtils.isNotBlank(name)) {
      criteria.andLike("name", "%" + name + "%");
    }
    if (StringUtils.isNotBlank(userId)) {
      criteria.andEqualTo("userid",  userId );
    }
    if (StringUtils.isNotBlank(payType)) {
      criteria.andEqualTo(
          "payType", payType);
    }
    if (StringUtils.isBlank(yearMonth)) {
      yearMonth = DateUtil.getYearMonth();
    }
    try {
      criteria.andLike("payTime", yearMonth+"%");

    } catch (Exception e) {
      e.printStackTrace();
    }
    int count = baseBiz.selectCountByExample(example);
    PageHelper.startPage(offset, limit);
    PageHelper.orderBy("crt_time " + orderStr);
    return new TableResultResponse<JsBills>(count, offset, limit,
        baseBiz.selectByExample(example));

  }

  @ApiOperation(value = "查询支付名称", notes = "查询支付名称")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "name", value = "名称", required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "payType", value = "类型：0收入 1支出", required = false, paramType = "query", dataType = "String")

  })
  @RequestMapping(value = "/name", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse<String> name(String name, String payType) {

    if (StringUtils.isBlank(name)) {
      return new ObjectRestResponse().rel(true).msg("请传入支付名称");
    }
    if (StringUtils.isBlank(payType)) {
      payType = BillEnum.INCOME.getKey();
    }
    List<String> list = baseBiz.selectName(getCurrentUserId(), name, payType);
    return new ObjectRestResponse().rel(true).result(list);

  }

  @ApiOperation(value = "查询支付总额", notes = "查询支付总额")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "yearMonth", value = "年月2018-03", required = false, paramType = "query", dataType = "String")
  })
  @RequestMapping(value = "/type", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse<JsBills> type(String yearMonth) {
    if (StringUtils.isBlank(yearMonth)) {
      yearMonth = DateUtil.getYearMonth();
    }
    try {
      String totalIncome = baseBiz
          .selectType(getCurrentUserId(),  yearMonth,BillEnum.INCOME.getKey());
      String totalEx = baseBiz
          .selectType(getCurrentUserId(), yearMonth, BillEnum.EXPENSES.getKey());
      HashMap<String, String> map = new HashMap<String, String>(2) {
        {
          put("totalIncome", totalIncome);
          put("totalEx", totalEx);
        }
      };
      return new ObjectRestResponse().rel(true).result(map);
    } catch (Exception e) {
      e.printStackTrace();
      return new ObjectRestResponse().rel(false).msg("未知错误:" + e.getMessage());
    }


  }

  @ApiOperation(value = "新增/编辑/查看", notes = "新增编辑查看")
  @RequestMapping(value = "/edit", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse edit(JsBills entity) {
    if (StringUtils.isBlank(entity.getId())) {
      return new ObjectRestResponse().rel(true).msg("账本ID不能为空");
    }
    entity = baseBiz.selectById(entity.getId());
    return new ObjectRestResponse().rel(true).msg("查询成功").result(entity);
  }

  @ApiOperation(value = "保存", notes = "保存")
  @RequestMapping(value = "/edit", method = RequestMethod.POST)
  @ResponseBody
  public ObjectRestResponse save(@RequestBody JsBills entity) {
    String type = "edit";
    if (StringUtils.isBlank(entity.getId())) {
      type = "insert";
      entity.setId(new IdUtil(1, 1).nextId() + "");
    }
    String userId = this.getCurrentUserId();

    if ( userId==null || userId.equals("") ) {
      //return new TableResultResponse<Address>(0, offset, limit,new ArrayList<Address>());
      userId="1";
    }
    entity.setUserid(userId);
    if (type.equals("insert")) {
      baseBiz.insertSelective(entity);
    } else {
      baseBiz.updateSelectiveById(entity);
    }
    return new ObjectRestResponse().rel(true).msg("保存成功");
  }


}
